package com.milling.business.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.milling.business.BusinessConstants;
import com.milling.business.GlobalVariable;
import com.milling.business.domain.WmsBoxInfo;
import com.milling.business.domain.WmsNeedleSortting;
import com.milling.business.mapper.WmsBoxInfoMapper;
import com.milling.business.mapper.WmsNeedleSorttingMapper;
import com.milling.business.service.IWmsNeedleSorttingService;
import com.milling.common.core.redis.RedisCache;
import com.milling.common.utils.DateUtils;
import com.milling.common.utils.StringUtils;
import com.milling.common.utils.modbus.ModbusServiceFactory;
import com.milling.common.utils.modbus.ModbusTcpService;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 * 分拣托盘Service业务层处理
 *
 * @author X
 * @date 2025-05-23
 */
@Service
public class WmsNeedleSorttingServiceImpl implements IWmsNeedleSorttingService
{
    private static final Logger logger = LoggerFactory.getLogger(WmsNeedleSorttingServiceImpl.class);

    @Autowired
    private WmsNeedleSorttingMapper wmsNeedleSorttingMapper;

    @Autowired
    private WmsBoxInfoMapper wmsBoxInfoMapper;

/*
    @Value("${modbus.sorting.host}")
    private String host;// = "192.168.237.178"; // 从配置文件或命令行参数中读取

    @Value("${modbus.sorting.port}")
    private int port;// = 502; // 从配置文件或命令行参数中读取

    @Value("${modbus.sorting.poolSize}")
    private int poolSize;// = 100; // 从配置文件或命令行参数中读取

    @Value("${modbus.sorting.slaveId}")
    private int slaveId;// = 1;
*/

    // 从参数中读取IP、端口、slaveId和连接池大小
    @Value("${modbus.sorting.host:192.168.237.178}")
    private String host; // 从配置文件或命令行参数中读取

    @Value("${modbus.sorting.port:502}")
    private int port; // 从配置文件或命令行参数中读取

    @Value("${modbus.sorting.poolSize:5}")
    private int poolSize; // 从配置文件或命令行参数中读取

    @Value("${modbus.sorting.slaveId:1}")
    private int slaveId;

    // 获取Modbus服务实例
    private ModbusTcpService modbusTcpService;

    @Autowired
    private RedisCache redisCache;
//    @Autowired
//    private AlertConfirmWebSocketHandler webSocketHandler;

    @PostConstruct
    public void init() {
        // 初始化 Modbus 服务
        modbusTcpService = ModbusServiceFactory.getModbusService(host, port, poolSize);
        logger.info("WmsNeedleSorttingServiceImpl Modbus服务初始化完成 - {}:{}", host, port);

        // 初始化扫码器连接
//        initConnection();
    }
    /**
     * 查询分拣托盘
     *
     * @param needleId 分拣托盘主键
     * @return 分拣托盘
     */
    @Override
    public WmsNeedleSortting selectWmsNeedleSorttingByNeedleId(Long needleId)
    {
        return wmsNeedleSorttingMapper.selectWmsNeedleSorttingByNeedleId(needleId);
    }

    /**
     * 查询分拣托盘列表
     *
     * @param wmsNeedleSortting 分拣托盘
     * @return 分拣托盘
     */
    @Override
    public List<WmsNeedleSortting> selectWmsNeedleSorttingList(WmsNeedleSortting wmsNeedleSortting)
    {
        return wmsNeedleSorttingMapper.selectWmsNeedleSorttingList(wmsNeedleSortting);
    }

    /**
     * 新增分拣托盘
     *
     * @param wmsNeedleSortting 分拣托盘
     * @return 结果
     */
    @Override
    public int insertWmsNeedleSortting(WmsNeedleSortting wmsNeedleSortting)
    {
        wmsNeedleSortting.setCreateTime(DateUtils.getNowDate());
        return wmsNeedleSorttingMapper.insertWmsNeedleSortting(wmsNeedleSortting);
    }

    /**
     * 修改分拣托盘
     *
     * @param wmsNeedleSortting 分拣托盘
     * @return 结果
     */
    @Override
    public int updateWmsNeedleSortting(WmsNeedleSortting wmsNeedleSortting)
    {
        wmsNeedleSortting.setUpdateTime(DateUtils.getNowDate());
        return wmsNeedleSorttingMapper.updateWmsNeedleSortting(wmsNeedleSortting);
    }

    /**
     * 批量删除分拣托盘
     *
     * @param needleIds 需要删除的分拣托盘主键
     * @return 结果
     */
    @Override
    public int deleteWmsNeedleSorttingByNeedleIds(Long[] needleIds)
    {
        return wmsNeedleSorttingMapper.deleteWmsNeedleSorttingByNeedleIds(needleIds);
    }

    /**
     * 删除分拣托盘信息
     *
     * @param needleId 分拣托盘主键
     * @return 结果
     */
    @Override
    public int deleteWmsNeedleSorttingByNeedleId(Long needleId)
    {
        return wmsNeedleSorttingMapper.deleteWmsNeedleSorttingByNeedleId(needleId);
    }

    /**
     * 补充分拣托盘料号，保证每个分拣托盘位都有针盒
     */
    public void fixSorttingNeedleBox() {
        WmsNeedleSortting wmsNeedleSortting = new WmsNeedleSortting();
        wmsNeedleSortting.setType(BusinessConstants.SORTTING_NEEDLE_TYPE_SORTTING);
        wmsNeedleSortting.setStatus(BusinessConstants.SORTTING_NEEDLE_STATUS_FEEDINGBOX);
        List<WmsNeedleSortting> wmsNeedleFeedingboxList = wmsNeedleSorttingMapper.selectWmsNeedleSorttingList(wmsNeedleSortting);
        if(null != wmsNeedleFeedingboxList && wmsNeedleFeedingboxList.size() > 0) {
            //有空盒上料任务未完成
            logger.info("有空盒上料任务未完成");
//            return false;
        } else {
//        wmsNeedleSortting.setType(BusinessConstants.SORTTING_NEEDLE_TYPE_SORTTING);
            wmsNeedleSortting.setStatus(BusinessConstants.SORTTING_NEEDLE_STATUS_NOBOX);
            List<WmsNeedleSortting> wmsNeedleSorttingList = wmsNeedleSorttingMapper.selectWmsNeedleSorttingList(wmsNeedleSortting);
            if (null != wmsNeedleSorttingList && wmsNeedleSorttingList.size() > 0) {
                wmsNeedleSortting = wmsNeedleSorttingList.get(0);
                //MODBUS写入 分拣针盒位置
                changeNeedleStatus(wmsNeedleSortting.getNeedleId(), BusinessConstants.SORTTING_NEEDLE_STATUS_FEEDINGBOX);//修改状态位 空盒上料中
//            D5001写入2， D5002写入 1成盅盒、2客户盒
                logger.info("[PC]通知PLC上空盒");
                try {
//                    changeNeedleStatus(wmsNeedleSortting.getNeedleId(), BusinessConstants.SORTTING_NEEDLE_STATUS_FEEDINGBOX);//修改状态位 空盒上料中

                    modbusTcpService.writeHoldingRegister(slaveId, 5013, 6);
                    logger.info("[PC]写入5013写入6完成。。。");
                    //第一个空盒集装箱
                    modbusTcpService.writeHoldingRegister(slaveId, 5002, 1);
                    logger.info("[PC]写入5002写入1完成。。。");
                    //补空盒入分拣托盘第几个盒子位
                    modbusTcpService.writeHoldingRegister(slaveId, 5003, wmsNeedleSortting.getNeedleId().intValue());
                    logger.info("[PLC]空位上盒地址5003写入完成" + wmsNeedleSortting.getNeedleId());

                    logger.info("[PC]通知PLC上空盒信号写入完成成功");
                } catch (ModbusTransportException ex) {
                    ex.printStackTrace();
                    logger.info("[PC]通知PLC上空盒信号写入完成失败");
                } catch (Exception ex) {
                    ex.printStackTrace();
                    logger.info("[PLC]扫码成功，给5000地址清0失败");
                }

/*
            ObjectPool<ModbusMaster> modbusMasterPool = ModbusMasterPoolFactory.createPool(host, port, poolSize);
            // 创建ModbusService实例
            ModbusTcpService modbusTcpService = new ModbusTcpServiceImpl(modbusMasterPool);
            logger.info("[PLC]开始空位上盒");
            try {
                changeNeedleStatus(wmsNeedleSortting.getNeedleId(), BusinessConstants.SORTTING_NEEDLE_STATUS_FEEDINGBOX);//修改状态位 空盒上料中

                modbusTcpService.writeHoldingRegister(slaveId, 5001, 2);
                //第一个空盒集装箱
                modbusTcpService.writeHoldingRegister(slaveId, 5002, 1);
                //补空盒入分拣托盘第几个盒子位
                modbusTcpService.writeHoldingRegister(slaveId, 5003, wmsNeedleSortting.getNeedleId().intValue());
                logger.info("[PLC]空位上盒地址写入完成。。。");
            } catch (ModbusTransportException ex) {
                ex.printStackTrace();
                logger.info("[PLC]空位上盒失败");
            } finally {
                modbusMasterPool.close();
            }
*/
//                return false;
            } else {
                logger.info("没有需要补充分拣托盘位，可以分拣");
                write50();
//                return true;
            }
        }
    }

    /**
     * 修改针盒状态
     * @param status
     * @param needleId
     */
    public void changeNeedleStatus(Long needleId, String status){
        WmsNeedleSortting wmsNeedleSortting = wmsNeedleSorttingMapper.selectWmsNeedleSorttingByNeedleId(needleId);
        wmsNeedleSortting.setStatus(status);
        wmsNeedleSorttingMapper.updateWmsNeedleSortting(wmsNeedleSortting);
    }

    public void write50(){
        // 创建连接池

//        Map<String, Integer> fullMap = new HashMap();
//        Map<String, Integer> mixMap = new HashMap();

        GlobalVariable.maxScanTimes = 0;

        try {
            modbusTcpService.writeHoldingRegister(slaveId,5013, 1);//不扫钻针
            logger.info("[PLC]不扫钻针，直接写入地址");

//            String message = "920000031311";//暂时写此值,同料码
//            "920000026334"
//            "920000030099"

//            String[] messageArray = new String[]{"920000031311", "920000026334", "920000030099", "920000029362"};
//            String message = "920000029362";
//            Random random = new Random();
//            message = messageArray[random.nextInt(messageArray.length)];

//            String message = GlobalVariable.SORTING_BOX_CODE;
            String message = redisCache.getCacheObject(GlobalVariable.SORTING_BOX_CODE);
            logger.info("分拣二维码码" + message);

//            String message = "920000029362";//非 同料码

//            String message = GlobalVariable.SORTING_BOX_CODE;
//            String message = "920000030099";//一支针

            modbusTcpService.writeHoldingRegister(slaveId,5001, 1);//直接分拣
            logger.info("[PLC]直接分拣，写入地址D5001");

            WmsBoxInfo wmsBoxInfo = new WmsBoxInfo();
            wmsBoxInfo.setBoxCode(message);
            wmsBoxInfo.setBoxStatus("0");

            List<WmsBoxInfo> list = wmsBoxInfoMapper.selectWmsBoxInfoList(wmsBoxInfo);
            if(null != list && list.size() > 0) {
                wmsBoxInfo = list.get(0);
                String boxData = wmsBoxInfo.getBoxData();
                String sameFlag = wmsBoxInfo.getSameFlag();

                JSONObject jsonObject = JSONObject.parseObject(boxData);
                // 提取顶层字段
                String boxId = jsonObject.getString("boxId");
                String boxType = jsonObject.getString("boxType");
                String drillInfos = jsonObject.getString("drillInfos");
                String[] drillInfoArray = drillInfos.split(","); // 将字符串按逗号分割成数组

                /*for (String drillInfo : drillInfoArray) {
                    if(StringUtils.isNotEmpty(drillInfo)) {
                        logger.info(drillInfo);
                    }
                }*/
                logger.info("boxId: " + boxId);
                logger.info("boxType: " + boxType);
                logger.info("drillInfos: " + drillInfos);

                if("FULL".equals(boxType)) {//满盒同料，给D5100 写入1000
                    logger.info("同料流程");
//                    GlobalVariable.GLOBAL_DRILL_INFO = drillInfos.trim();
                    redisCache.setCacheObject(GlobalVariable.GLOBAL_DRILL_INFO, drillInfos.trim());
                    String drillSize = drillInfos.substring(0, 4);
                    logger.info("同料下料钻针尺寸: " + drillSize);
//                    GlobalVariable.GLOBAL_DRILL_SIZE = drillSize;//记录此盒的钻针信息，后续写入钻针尺寸时要用到
                    redisCache.setCacheObject(GlobalVariable.GLOBAL_DRILL_SIZE, drillSize);

                    short[] arr = new short[50];
                    for (int i = 0; i < arr.length; i++) {
                        arr[i] = 1000;
                    }
                    modbusTcpService.writeHoldingRegisters(slaveId, 5100, arr);
                    logger.info("[PLC]全同料，写入地址5100成功");

                } else if("MIX".equals(boxType)) {//非同料，抓到中转区
                    logger.info("不 同料流程");
                    //整理需要分拣的料号

                    //分拣盘上有多少中未满料盒
                    //分拣盘上有多少个空位，可以补充料盒(空盒上料)

                    //分拣位置不够时，需做 未满盒下料

                    //待分拣料号总数
                    Map<String, Integer> map = new HashMap<>();
                    for (String drillInfo : drillInfoArray) {
                        if(StringUtils.isNotEmpty(drillInfo)) {
                            logger.info(drillInfo);
                            Integer count = map.get(drillInfo);
                            if (count == null) {
                                count = 1;
                            } else {
                                count++;
                            }
                            map.put(drillInfo.trim(), count);
                        }
                    }
                    int mapCount = map.size();

                    WmsNeedleSortting wmsNeedleSortting = new WmsNeedleSortting();
                    wmsNeedleSortting.setStatus(BusinessConstants.SORTTING_NEEDLE_STATUS_NORMAL);
                    wmsNeedleSortting.setType(BusinessConstants.SORTTING_NEEDLE_TYPE_SORTTING);

                    List<WmsNeedleSortting> normalDrillSorttingList = selectWmsNeedleSorttingList(wmsNeedleSortting);
                    int normalSize = 0;//分拣托盘有适配的料号
                    int blankSize = 0;
                    List blankList = new ArrayList();
                    Map<String, Long> normalMap = new HashMap();
                    String noDrillString = "";
                    for (WmsNeedleSortting wmsNeedleSortting1 : normalDrillSorttingList) {
                        Long needleId = wmsNeedleSortting1.getNeedleId();
                        String tempDrillInfo = wmsNeedleSortting1.getDrillInfo();
                        if (StringUtils.isNotEmpty(tempDrillInfo)) {
//                            logger.info("分拣托盘的料号：" + tempDrillInfo);
//                            logger.info("待分拣的针号：" + map.get(tempDrillInfo.trim()));
                            if(map.get(tempDrillInfo.trim()) != null) {//如果有待分拣料号的位置
                                normalSize++;

                                normalMap.put(tempDrillInfo, needleId);
                            }
                        } else {
                            if (wmsNeedleSortting1.getDrillCount() == null || wmsNeedleSortting1.getDrillCount() == 0) {
                                //空位置，有盒
                                blankSize++;
                                if(StringUtils.isNotEmpty(noDrillString)) {
                                    noDrillString += "," + needleId;
                                } else {
                                    noDrillString = needleId.toString();
                                }
                                blankList.add(needleId);//未使用盒子位

//                                    blankMap.put(needleId.intValue(), "0");//未使用
                            }
                        }
                    }
                    normalSize = normalMap.size();
                    logger.info("待分拣料号数量：" + mapCount);
                    logger.info("分拣托盘有的料号数量：" + normalSize);
                    logger.info("分拣托盘有的空盒位数量：" + blankSize);

                    if(mapCount > normalSize + blankSize) {//分拣托盘有料位+空盒位不足
                        logger.info("分拣托盘有料位+空盒位不足，请执行异常下料!!");
                        logger.info("分拣托盘有料位+空盒位不足，请执行异常下料!!");
                        //分拣位不足，请执行异常下料
                    } else {
                        short[] holes = new short[50];

                        logger.info("数组SIZE：" + drillInfoArray.length);
                        if (mapCount > normalSize) {//分拣位有料不足，需使用空盒位，充足
                            int z = 0;
                            for (int m = 0; m < 50; m++) {
//                            for (int m = 0; m < drillInfoArray.length; m++) {
//                            for (int m = drillInfoArray.length - 1; m >= 0; m--) {
                                String drillInfo = "";
                                try {
                                    drillInfo = drillInfoArray[m];
                                } catch (Exception e) {
                                    logger.info("数组越界，空位!!");
                                }
                                if (StringUtils.isNotEmpty(drillInfo)) {
                                    drillInfo = drillInfo.trim();
                                    if (null != normalMap.get(drillInfo)) {
                                        int needleId = normalMap.get(drillInfo).intValue();
                                        holes[49 - m] = (short)needleId;
//                                        modbusTcpService.writeHoldingRegister(slaveId, 5100 + (49 - m), needleId);
//                                        logger.info("写入有料位置：" + (5100 + (49 - m)) + " 分拣托盘位置 " + needleId);
                                    } else {
                                        String drillSize = drillInfo.substring(0, 4);
                                        String drillType = drillInfo.substring(4, 5);
                                        String drillGrindCount = drillInfo.substring(7, 8);

                                        //默认刃长 和 厂牌都为1
                                        String m_Drill_Edge = "1";    //钻针刃长
                                        String m_Drill_Factory ="1";    //钻针厂牌


                                        int needleId = ((Long)blankList.get(z)).intValue();
                                        WmsNeedleSortting wmsNeedleSorttingDB = selectWmsNeedleSorttingByNeedleId(new Long(needleId));
                                        wmsNeedleSorttingDB.setType(BusinessConstants.SORTTING_NEEDLE_TYPE_SORTTING);
                                        wmsNeedleSorttingDB.setStatus(BusinessConstants.SORTTING_NEEDLE_STATUS_NORMAL);
                                        wmsNeedleSorttingDB.setDrillInfo(drillInfo);
                                        wmsNeedleSorttingDB.setDrillSize(drillSize);
                                        wmsNeedleSorttingDB.setDrillType(drillType);
                                        wmsNeedleSorttingDB.setDrillEdge(m_Drill_Edge);
                                        wmsNeedleSorttingDB.setDrillFactory(m_Drill_Factory);
                                        wmsNeedleSorttingDB.setDrillGrindCount(new Long(drillGrindCount));
                                        updateWmsNeedleSortting(wmsNeedleSorttingDB);

                                        normalMap.put(drillInfo, new Long(needleId));
                                        holes[49 - m] = (short)needleId;
//                                        modbusTcpService.writeHoldingRegister(slaveId, 5100 + (49 - m), needleId);
//                                        logger.info("写入新盒位置：" + (5100 + (49 - m)) + " 分拣托盘位置 " + needleId);
                                        z++;
                                    }
                                } else {
                                    holes[49 - m] = 100;
//                                    modbusTcpService.writeHoldingRegister(slaveId, 5100 + (49 - m), 100);
//                                    logger.info("空针位置：" + (5100 + (49 - m) + " 写入100 "));
                                }
                            }
                        } else {
//                            short[] holes = new short[50];
                            //直接写入50个位置
                            for (int m = 0; m < 50; m++) {
//                            for (int m = 0; m < drillInfoArray.length; m++) {
                                String drillInfo = "";
                                try {
                                    drillInfo = drillInfoArray[m];
                                } catch (Exception e) {
                                    logger.info("数组越界，空位!!");
                                }
                                if (StringUtils.isNotEmpty(drillInfo)) {
                                    drillInfo = drillInfo.trim();
                                    //写入位置
                                    Long needleId = normalMap.get(drillInfo);
//                                    holes[m] = needleId.shortValue();
                                    holes[49 - m] = needleId.shortValue();
//                                    logger.info("写入有料位置I：" + (49 - m) + " 分拣托盘位置 " + needleId);
                                } else {
                                    holes[49 - m] = 100;
//                                    holes[m] = 100;
//                                    logger.info("写入空针位置I：" + (49 - m) + " 写入100 ");
//                                    logger.info("空针位置：" + (5100 + (49 - m) + " 写入100 "));

                                }
                            }
//                            logger.info("写入分拣托盘位置开始");
//                            modbusTcpService.writeHoldingRegisters(slaveId, 5100, holes);
//                            logger.info("写入分拣托盘位置：" + Arrays.toString(holes));
//                            logger.info("写入分拣托盘位置完成：");
                        }
                        logger.info("写入分拣托盘位置开始");
                        modbusTcpService.writeHoldingRegisters(slaveId, 5100, holes);
                        logger.info("写入分拣托盘位置：" + Arrays.toString(holes));
                        logger.info("写入分拣托盘位置完成：");
                    }
                }
            } else {
                logger.info("此二维码没有待分拣信息，无法分拣");

//                String alertMessage = "{\"type\":\"alert\",\"title\":\"提示信息\",\"content\":\"当前托盘已分拣完成，需要继续分拣吗？\",\"buttons\":{\"continueSorting\":\"继续\",\"completeSorting\":\"结束\"}}";
//                webSocketHandler.sendAlert(alertMessage);
//                logger.info("[" + new Date() + "] 是否继续分拣提示信息已发送");

//                String alertMessage = "{\"type\":\"alert\",\"title\":\"提示信息\",\"content\":\"当前针盒二维码"+message+"没有配针信息，请检查\",\"buttons\":{\"sortingBoxinfoOk\":\"确定\"}}";
//                webSocketHandler.sendAlert(alertMessage);

            }

            //扫码成功,继续扫其他码
//            String[] tt = GlobalVariable.CONFIG_BOX_CODE;
//            GlobalVariable.CONFIG_BOX_ID = GlobalVariable.CONFIG_BOX_ID + 1;

        } catch (ModbusTransportException ex) {
            ex.printStackTrace();
            logger.info("处理待分拣盒信息失败");
        } catch (Exception ex) {
            ex.printStackTrace();
            logger.info("[PLC]扫码成功，给5000地址清0失败");
        }

/*
        try {
            Iterator<Map.Entry<String, Integer>> iterator3 = mixMap.entrySet().iterator();

            while (iterator3.hasNext()) {
                Map.Entry<String, Integer> entry = iterator3.next();
                String addr = entry.getKey();
                int value = entry.getValue();
                modbusTcpService.writeHoldingRegister(slaveId, new Integer(addr), value);
                logger.info("addr:" + addr + " value:" + value);
            }
        } catch (ModbusTransportException ex) {
            ex.printStackTrace();
            logger.info("批量写入50个地址失败");
        } catch (Exception ex) {
            ex.printStackTrace();
            logger.info("[PLC]批量写入地址失败");
        }
*/
    }

    public void sysncNeedleSortingStatus() {
//        logger.info("#######分拣区数据同步处理开始####");
        long startTime = System.currentTimeMillis(); // 记录开始时间

        Map needleStockMap = new HashMap();

        try{
            short[] registers = modbusTcpService.readHoldingRegisters(slaveId, 5900, 80);
            for (int i = 1; i <= 80; i++) {
                String key = "NEEDLE_ID" + (i);
                int value = registers[(i-1)];
//                logger.info("key: " + key + " || value: " + value);
                needleStockMap.put(key, value);
            }
        } catch (ModbusTransportException e) {
            e.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        //通过REDIS，刷新NEEDLE配针缓存区数据
        WmsNeedleSortting wmsNeedleSortting = new WmsNeedleSortting();
//        wmsNeedleSortting.setStatus(BusinessConstants.SORTTING_NEEDLE_STATUS_NORMAL);
//        wmsNeedleSortting.setType(BusinessConstants.SORTTING_NEEDLE_TYPE_SORTTING);
        List<WmsNeedleSortting> needSorting = wmsNeedleSorttingMapper.selectWmsNeedleSorttingList(wmsNeedleSortting);
//        logger.info("库位数量 " + needSorting.size());
        for (int i = 0; i < needSorting.size(); i++) {
            WmsNeedleSortting wmsNeedleSorting = needSorting.get(i);

//            logger.info("分拣区位 NEEDLE_ID" + (i + 1));
            int needleCount = (Integer) needleStockMap.get("NEEDLE_ID" + (i + 1));
            if (needleCount == 0) {
//                logger.info("分拣区位 {} 钻针数为0", wmsNeedleSorting.getNeedleId());
                //清空分拣区位数据，状态  空闲
//                wmsNeedleSorting.setStatus(BusinessConstants.SORTTING_NEEDLE_STATUS_NORMAL);
//                wmsNeedleSorting.setDrillSize(null);
//                wmsNeedleSorting.setDrillInfo(null);
//                wmsNeedleSorting.setDrillType(null);
//                wmsNeedleSorting.setDrillEdge(null);
//                wmsNeedleSorting.setDrillFactory(null);
//                wmsNeedleSorting.setDrillGrindCount(null);
                wmsNeedleSorting.setDrillCount(new Long(0));
                wmsNeedleSorting.setUpdateTime(DateUtils.getNowDate());
                //其他数据暂不清除
            } else {
                //状态   有货
//                if(BusinessConstants.NEEDLE_STATUS_1.equals(wmsNeedleSorting.getStatus())) {
//                    wmsNeedleSorting.setStatus(BusinessConstants.NEEDLE_STATUS_2);
//                }
//                logger.info("分拣区位 {} 钻针数大于0", wmsNeedleSorting.getNeedleId());
                wmsNeedleSorting.setDrillCount(new Long(needleCount));
                wmsNeedleSorting.setUpdateTime(DateUtils.getNowDate());

            }
            wmsNeedleSorttingMapper.updateWmsNeedleSortting(wmsNeedleSorting);
        }

//        logger.info("#######分拣区数据同步处理结束");
        long endTime = System.currentTimeMillis(); // 记录结束时间
        long duration = endTime - startTime; // 计算执行时间
//        logger.info("分拣区数据同步处理 executed in {} ms", duration); // 输出执行时间
    }

    public void initSortingParam() {
        // 初始化新增的全局参数
        redisCache.setCacheObject(GlobalVariable.GLOBAL_DRILL_SIZE, "0");
        redisCache.setCacheObject(GlobalVariable.GLOBAL_DRILL_INFO, "");
        redisCache.setCacheObject(GlobalVariable.SORTING_BOX_CODE, "");
        redisCache.setCacheObject(GlobalVariable.SORTING_BOX_ID, 0);

        // 初始化分拣盒数组（12个空字符串）
        List<String> emptySortingList = Arrays.asList(new String[12]);
        if(null != emptySortingList && emptySortingList.size() > 0) {
            logger.info("初始化吗清单 " + emptySortingList.size());
            for (int i = 0; i < emptySortingList.size(); i++) {
                logger.info("清单第 {} 个，数据为【 {} 】", i, emptySortingList.get(i));
            }
        }
        redisCache.deleteObject(GlobalVariable.SORTING_BOX_CODE_ARRAY);
//        redisCache.setCacheList(GlobalVariable.SORTING_BOX_CODE_ARRAY, emptySortingList);
        redisCache.setCacheObject(GlobalVariable.SORTING_BOX_CODE_ARRAY, emptySortingList);
    }

    private String getStringCache(String key) {
        return redisCache.getCacheObject(key) == null ? "" : (String) redisCache.getCacheObject(key);
    }

    private int getIntCache(String key) {
        return redisCache.getCacheObject(key) == null ? 0 : (int) redisCache.getCacheObject(key);
    }

}
